<template>
  <div class="app-container">
    <!-- <t-Search /> -->
    <el-form :model="param" :rules="pageRules" ref="publishRef" label-width="0">
      <el-card class="form_card">
        <span class="_before">基本信息</span>
        <div style="margin:40px 40px 0 40px">
          <el-row style="width:600px;min-width: 400px;">
            <el-col :span="11">
              <el-form-item prop="boxStartCity">
                <div>
                  <redStar />售箱城市
                </div>
                <template v-if="route.query.type == 'release'">
                  <city-select ref="startCityRef" v-model="param.boxStartCity" :disabled="isInfo" :needInfo="true"  :cityList="startCityList"
                  @cityId="startCityInfo" @clear="clear" style="width: 100%;"></city-select>
                </template>
                <template v-else>
                  <city-select ref="startCityRef" v-model="param.boxStartCity" :needInfo="true" disabled :cityList="startCityList"
                  @cityId="startCityInfo" @clear="clear" style="width: 100%;"></city-select>
                </template>
                
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-card>

      <el-card class="form_card" style="margin-top: 15px;">
        <span class="_before">售箱信息</span>
        <div style="margin:40px 40px 0 40px">
          <el-row :gutter="10" style="background-color: #eee;padding:20px;border-radius: 2px; ">
            <el-col :span="22">
              <boxPriceList ref="boxPriceListRef" :isSell="true" :priceList="param.priceList"  @currency="publishCurrency" :disabled="!param.boxStartCity[0] || isInfo"></boxPriceList>
            </el-col>
          </el-row>

          <el-form-item prop="payCurrency" style="width:240px;margin-top: 20px;">
            <redStar />
            <div style="width:80px">可结算币种</div>
            <el-checkbox-group v-model="param.payCurrency" :disabled="isInfo">
                <el-checkbox label="人民币（CNY）" value="CNY" :disabled="param.isCheckCNY"/>
                <el-checkbox label="美元（USD）" value="USD"  :disabled="param.isCheckUSD"/>
            </el-checkbox-group>
          </el-form-item>

          <el-form-item prop="productionDate" style="width:240px;">
            <redStar />
            <div>生产日期范围</div>
            <el-date-picker v-model="param.productionDate" :disabled="isInfo" :max="new Date" type="yearrange"  range-separator="~"
              start-placeholder="开始日期" end-placeholder="结束日期" />
          </el-form-item>

          <el-form-item prop="invoiceType" style="margin-top: 20px;">
            <redStar />
            <div style="width:80px;">发票类型</div>
            <!-- 5-增值税普通发票 15-形式发票 20-其它 -->
            <el-checkbox-group v-model="param.invoiceType" :disabled="isInfo">
              <el-checkbox label="增值税普通发票" value="5" />
              <el-checkbox label="增值税专用发票" value="10" />
              <el-checkbox label="形式发票" value="15" />
            </el-checkbox-group>
          </el-form-item>
          <el-form-item style="width:240px">
            <div>总售箱量</div>
            <el-input v-model="totalInventory" placeholder="请输入" disabled style="width: 100%">
              <template #append>个</template>
            </el-input>
          </el-form-item>
        </div>
      </el-card>
      <el-card class="marginTop20">
        <span class="_before">发布人</span>
        <el-form style="width:240px">
          <el-row class="marginTop20">
            <el-col :offset="3" :span="8" align="middle"><redStar />销售人</el-col>
            <el-col :span="10" align="middle"><el-input v-model="param.nickname " placeholder="请输入" disabled style="width: 100%"></el-input></el-col>
          </el-row>
        </el-form>
      </el-card>
      <el-card class="form_card" style="margin-top: 15px;">
        <span class="_before">图文描述</span>
        <div style="margin:40px 40px 0 40px">
          <el-form-item>
            <redStar />
            <div>主图</div>
            <div style="width:100%">
              <div class="div-box-dark">
                <upload-Img ref="uploadImgRef" :urlList="param.showMainImgList" :disabledUpload="isInfo" @uploadSccess="uploadMainSccess"
                  @uploadRemoveSccess="uploadRemoveMainImgSccess" style="width:1000px;height: 1000px;" />
                <p v-if="!isInfo">请上传1:1主图，主图大小不能超过3M，建议图片像素高于700*700px</p>
              </div>
            </div>
          </el-form-item>
          <el-form-item>
            <h3>
              详情描述 <span style="color: #999999;font-size: 12px;">详情图片要求款:750px,高无限制，大小最大不超过10M</span>
            </h3>
            <div style="width:100%;min-height:100px;min-width: 600px;">
              <div v-for="(mark, index) in param.marks" :key="index">
                <div style="background-color: #f4f4f5;box-sizing: border-box;padding: 10px;">
                  <upload-Img :ref="(el) => handleSetInputMap(el, index)" :disabledUpload="isInfo" :urlList="mark.imgInfo"
                    @uploadSccess="uploadDetailSccess($event, index)"
                    @uploadRemoveSccess="uploadRemoveDetailImgSccess($event, index)"
                    style="width:1000px;height: 1000px; " />
                  <el-input v-model="mark.textVal" placeholder="在这里介绍您的集装箱" :disabled="isInfo" type="textarea" rows="2" show-word-limit
                    maxlength="200" style="width: 90%;" />
                  <el-button :icon="CloseBold" type="info"  v-if="!isInfo" circle @click="handleClose(index)"
                    style="width:10px;height:10px;margin-top: -30px;margin-left: 10px;"></el-button>
                </div>
              </div>
              <el-button v-if="!isInfo" :icon="Plus" type="info" size="small" @click="handleAdd">新增描述</el-button>
            </div>
          </el-form-item>
        </div>
      </el-card>
      <el-card class="marginTop20" v-if="!isInfo">
        <el-form-item>
          <div style="height: 50px;width: 100%;"></div>
          <div v-if="param.isLoading" style="margin:auto;color: chocolate;">数据提交中......</div>
          <div v-else style="width: 100%;">
            <el-row justify="center">
              <el-col :span="2" align="middle"><el-button type="primary" round  @click="onSave('save')">保存待发布</el-button></el-col>
              <el-col v-if="route.query.type == 'release'" :span="2" align="middle"><el-button type="warning" round @click="onSave('putWarehouse')">放入仓库</el-button></el-col>
              <el-col v-else :span="5" align="middle" ><el-icon style="color: #46c906;"><CircleCheckFilled /></el-icon><span>最后保存于{{formatDate(param.updateTime)}}</span></el-col>
              <el-col :span="2" align="middle"><el-button type="success" round @click="onSave('publish')">立即发布</el-button></el-col>
            </el-row>
          </div>
        </el-form-item>
    </el-card>
    </el-form>
    <!-- dialog -->
    <el-dialog v-model="param.dialogVisible" :title="param.operate == 'add' ? '新增' : '删除'" width="500">
      <!-- <span>This is a message</span> -->
      <el-input v-if="param.operate == 'add'" v-model="param.addElement"></el-input>
      <span v-else> 确认删除？</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="param.dialogVisible = false">
            取消
          </el-button>
          <el-button @click="handleOk">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { Plus, Minus, Delete, CloseBold } from '@element-plus/icons-vue'
import {formatDate} from '@/utils'
import { computed, getCurrentInstance, onActivated, onMounted, reactive, ref, watch } from 'vue';
import uploadImg from '@/components/upload/img.vue'
import citySelect from '@/components/citySelect'
import { useRoute, useRouter } from 'vue-router';
import orderInfo from '@/store/modules/order'
import boxPriceList from '@/views/components/boxPriceList'
import { ElMessage } from 'element-plus';
import Cookies from "js-cookie";
import { saleBoxTobeReleased, saleBoxSubmit,saleBoxInWarehouse, getReleaseSalesInfo } from '@/api/boxDeal/boxSeel'

import type { FormInstance } from 'element-plus'
import redStar from '@/views/components/redStar.vue';
const router = useRouter();
const route = useRoute();

let param = reactive({
  priceList: [{ boxType: 5, boxCondition: 5, unitPrice: 1, totalWeight: "30480/32500KG", inventory: 0, currency: 'CNY' }],
  productionDate: [],
  payCurrency: ['CNY'],
  currency: 'CNY',
  invoiceType: ['5'],
  boxSize: '40HQ',
  boxCase: ['fit'],
  loading: false,
  boxSizeHistory: {}, // eg:{40HQ:[{ size: string; info: any; price: string; num: string; }],20HQ:[],40GP:[],200GP:[]} 
  totalWeight: 1,
  weightOptions: [
    { value: 1, label: '30480KG' },
    { value: 2, label: '32500KG' },
  ],
  mode: 5,
  modeList: [
    { value: 5, label: '立即上架' },
    { value: 10, label: '放入仓库' },
  ],
  marks: [{ textVal: '' }],
  period: '',
  //  const filterSize = { 5: '40HQ', 10: '40GP', 15: '20HQ', 20: '20GP' }
  // const filterInfo = { 15: '适货', 10: '次新', 5: '全新', 20: '混提' }
  caseList: [
    { value: 'fit', label: '适货' },
    { value: 'nextNew', label: '次新' },
    { value: 'allNew', label: '全新' },
    { value: 'mix', label: '混提' },
  ],
  sizeList: [
    { value: '40HQ', label: '40HQ' },
    { value: '40GP', label: '40GP' },
    { value: '20HQ', label: '20HQ' },
    { value: '20GP', label: '20GP' },
  ],
  boxStartCity: [],
  boxBackCity: [],
  boxStartCityData: {},
  boxBackCityData: [],
  startCityOptions: [],
  backCityOptions: [],
  dialogVisible: false,
  operate: '',
  addElement: '',
  addType: 'case', // case,size
  overdueFeeDay: 0,
  isLoading:false,
  nickname:"",
  isCheckCNY:true, // 可结算币种默认选中
  isCheckUSD:false,
  updateTime:'' //更新日期
})


const validateProductionDate = (rule: any, value: any, callback: any) => {
  const now = new Date()
  const end = new Date(value[1])
  if (end > now) {
    callback(new Error('结束日期不能大于今天'))
  } else {
    callback()
  }
}


const pageRules = reactive({
  productionDate: [
    { required: true, message: '请完善生产日期范围', trigger: 'change' },
  ],
  payCurrency: [
    { required: true, message: '请选择支持币种', trigger: 'change' },
  ],
  invoiceType: [
    { required: true, message: '请选择发票类型', trigger: 'change' }
  ],
})

const startCityList = ref([])
const editId = ref(null)
const isInfo=ref(false)
onActivated(() => {
  param.marks = [{ textVal: '', imgInfo: [] }]
  param.showMainImgList = []
  param.invoiceType = ['5']
  param.productionDate = []
  param.priceList = [{ boxType: 5, boxCondition: 5, unitPrice: 1, totalWeight: "30480/32500KG", inventory: 0, currency: 'CNY' }]
  const rowData = orderInfo().rowData
  param.nickname = JSON.parse(Cookies.get("User-Info"))?.nickname
  if (!rowData) return
  showData(rowData)
})

// 初始化获取数据
const showData = async (rowData: any) => {
  if (!rowData) return
  editId.value = rowData.id
   if(rowData?.isInfo){
    isInfo.value=rowData.isInfo
  }
  if (editId.value) {
    await getReleaseSalesInfo(editId.value).then(async (res: any) => {
      const val = res.data
      //城市展示  
      startCityList.value = [{ value: val.carryCityId, label: val.carryCityName, countryId: val.carryCountryId, countryCName: val.carryCountryName }]
      // backCityList.value = [{ value: val.returnCityId, label: val.returnCityName, countryId: val.returnCountryId, countryCName: val.returnCountryName }]
      param.boxStartCity = [val.carryCityId]
      // param.boxBackCity = val.returnCityId
      //箱型箱况  
      param.priceList = val.releaseSalePriceList.map(item => {
        return {
          boxType: item.boxType,
          boxCondition: item.boxCondition,
          unitPrice: item.unitPrice,
          totalWeight: item.totalWeight,
          inventory: item.inventory,
          currency: item.currency
        }
      })
      //其他
      param.productionDate = [val.productionDateStart, val.productionDateEnd]
      param.payCurrency = val.payCurrency.split(',')
      param.invoiceType = [val.invoiceType]
      param.boxUsagePeriod = val.boxUsagePeriod
      param.isLoading = false
      param.marks = JSON.parse(val.detailFileList) || []
      // param.remark = val.remark
      param.showMainImgList = JSON.parse(val.mainFileList)
      param.currency = val.releaseSalePriceList[0].currency
      param.invoiceType = val.invoiceType.split(',')
      param.updateTime = val.updateTime
    })
  }
  if (!editId.value) {
    clearData()
  }
}

//清空数据
const clearData = () => {
  startCityList.value = [] //city置空
  param.priceList = [{ boxType: 5, boxCondition: 5, unitPrice: 1, totalWeight: "30480/32500KG", inventory: 0, currency: 'CNY' }]
  param.currency = 'USD'
  param.productionDate = []
  param.showMainImgList = []
  param.marks = [{ textVal: '', imgInfo: [] }]
}

// 获取城市和库存
const startCityInfo = (id: any, data: any) => {
  param.boxStartCity = [id]
  param.boxStartCityData = data
}
const clear = () => {
  param.boxStartCity = []
  param.boxStartCityData = {}
  startCityList.value = [] //city置空
  param.priceList = [{ boxType: 5, boxCondition: 5, unitPrice: 1, totalWeight: "30480/32500KG", inventory: 0, currency: 'CNY' }]
  param.currency = 'USD'
}

//总库存
const totalInventory = computed(() => {
  let num = 0
  if (param.priceList && param.priceList.length > 0) {
    num = param.priceList.reduce((pre, cur) => {
      return pre + cur.inventory
    }, 0)
  }
  return num
})

//发布卖箱-默认币种
const currencyChange = (val: any) => {
  param.priceList.forEach((el: any) => {
    el.currency = val
  })
  autoPush()
}

// 支持结算币种自动添加
const autoPush = () => {
  const payCurrencyExist = param.payCurrency.findIndex((item: any) => {
    return item == param.currency
  })
  if (payCurrencyExist < 0) {
    param.payCurrency.push(param.currency)
  }
}

// marks
const handleClose = (val: any) => {
  param.marks.splice(val, 1)
}
const handleAdd = (val: any) => {
  param.marks.push({ textVal: '' })
}

const handleOk = () => {
  param.dialogVisible = false
  if (param.operate == 'add') {
    if (param.addType == 'case') {
      let index = param.caseList.length
      param.caseList.push({ value: 'addElement' + index, label: param.addElement })
    }
    if (param.addType == 'size') {
      param.sizeList.push({ value: param.addElement, label: param.addElement })
    }
    param.addElement = ''
  }
  if (param.operate == 'delete') {
    if (param.addType == 'size') {// param.boxSize
      const index = param.sizeList.findIndex((item: any) => {
        return item.value == param.boxSize
      })
      if (index != -1) {
        param.sizeList.splice(index, 1)
      }
    }
    if (param.addType == 'case') {//param.boxCase
      param.boxCase.map((val: any) => {
        let index = param.caseList.findIndex((item: any) => {
          return item.value == val
        })
        if (index != -1) {
          // indexList.push(index)
          param.caseList.splice(index, 1)
        }
      })
    }
  }
}

//校验
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

//上传成功的 
const uploadMainSccess = (data: any) => {
  param.showMainImgList.push(data)
}
const uploadDetailSccess = (data: any, index: number) => {
  let mark = param.marks[index]
  mark.imgInfo.push(data)
}

//img删除成功
const uploadRemoveMainImgSccess = (data: any) => {
  let index = param.showMainImgList.findIndex((item: any) => {
    return item.uid == data.uid
  })
  if (index != -1) {
    param.showMainImgList.splice(index, 1)
  }
}
const uploadRemoveDetailImgSccess = (data: any, index: number) => {
  let mark = param.marks[index]
  let index1 = mark.imgInfo.findIndex((item: any) => {
    return item.uid == data.uid
  })
  if (index1 != -1) {
    mark.imgInfo.splice(index1, 1)
  }
  if (mark.imgInfo.length == 0 && !mark.textVal) {
    param.marks.splice(index, 1)
  }
}

// upload img
const uploadImgRef = ref()
const uploadRef = {}
const handleSetInputMap = (el, index: number) => {
  if (el) {
    uploadRef[`imgRef${index}`] = el;
  }
};

//上传文件
const uploadFile = async (file: any) => {
  let result: any = {}
  let formData = new FormData()
  formData.append('file', file.raw)
  await uploadFile(formData).then((res: any) => {
    result = res.data
  })
}

// 保存/发布
const { proxy } = getCurrentInstance();
const boxPriceListRef = ref({ priceList: [] })
const onSave = async (opr: any) => {
  param.isLoading = true
  const isExist = boxPriceListRef.value.isExist
  if (isExist) {
    return ElMessage.warning('请处理重复数据！')
  }
  let template = {
    "payCurrency": param.payCurrency.join(','),
    "invoiceType": param.invoiceType.join(','),
    "productionDateStart": param.productionDate[0],
    "productionDateEnd": param.productionDate[1],
    "remark": param.remark,
    "mainFileList": JSON.stringify(param.showMainImgList), //主图
    "detailFileList": JSON.stringify(param.marks), //详情信息 textVal
    "releaseSalePriceList": boxPriceListRef.value.getPriceList(),
  }
  if (editId.value) {
    const startCity = startCityList.value[0]
    let obj = {
      "id": editId.value,
      "carryCityId": startCity.value,
      "carryCityName": startCity.label,
      "carryCountryId": startCity.countryId,
      "carryCountryName": startCity.countryCName,
    }
    Object.assign(template, obj)
  }
  if (param.boxStartCityData.id) {
    const startCity = param.boxStartCityData
    let obj = {
      "carryCityId": startCity.id,
      "carryCityName": startCity.cityCName,
      "carryCountryId": startCity.countryId,
      "carryCountryName": startCity.countryCName
    }
    Object.assign(template, obj)
  }
  // return
  if (opr == 'save') { // 保存待发布
    await saleBoxTobeReleased(template).then((res: any) => {
      param.isLoading = false
      // resetForm(publishRef.value)
      router.push('mySellBox')
    }).catch((err: any) => {
      setTimeout(() => {
        param.isLoading = false
      }, 2000)
    })
  }
  if(opr == 'putWarehouse'){ // 放入仓库
    await saleBoxInWarehouse(template).then((res: any) => {
      param.isLoading = false
      router.push('mySellBox')
      ElMessage.success('放入仓库成功')
    }).catch((err: any) => {
      setTimeout(() => {
        param.isLoading = false
      }, 2000)
    })
  }
  if (opr == 'publish') {
    proxy.$refs.publishRef.validate(valid => { // 立即发布
      if (!valid) {
        param.isLoading = false
        return
      }
      if (param.showMainImgList.length === 0) {
        param.isLoading = false
        return ElMessage.warning('请上传主图！')
      }
      // if (param.marks.length == 0 || !param.marks[0].imgInfo || param.marks[0].imgInfo.length === 0) {
      //   param.isLoading = false
      //   return ElMessage.warning('请上传详情图！')
      // }
      saleBoxSubmit(template).then((res: any) => {
        param.isLoading = false
        router.push('mySellBox')
      }).catch((err: any) => {
        setTimeout(() => {
          param.isLoading = false
        }, 2000)
      })
    })//
  }
}

//根据租箱规格选择的币种 筛选可结算币种
const publishCurrency = (val: any) => {
  param.payCurrency.length = 0 
  param.payCurrency.push(val)
  if(val =="CNY"){
    param.isCheckCNY = true
    param.isCheckUSD = false
  }else if(val == "USD"){
    param.isCheckCNY = false
    param.isCheckUSD = true
  }
}

</script>
<style scoped>
.tagCard {
  background-color: WhiteSmoke;
  border: 1px solid #DCDCDC;
  border-size: border-box;
  padding: 10px;
  border-radius: 5px;
  margin-right: 5px
}
</style>